import React, { useState, useEffect, useRef } from "react";
import axios from "axios";
import {
  Button,
  PageHeader,
  Steps,
  Space,
  Form,
  Input,
  Select,
  message,
  notification,
} from "antd";
import style from "./News.module.css";
import NewsEditor from "./components/NewsEditor";
const { Option } = Select;
const { Step } = Steps;

export default function NewsAdd(props) {
  const [current, setCurrent] = useState(0);

  const handleNext = async () => {
    if (current === 0) {
      try {
        const values = await NewsForm.current.validateFields();
        setFormInfo(values);
      } catch (error) {
        return;
      }
    } else {
      if (content === "" || content.trim() === "<p></p>") {
        message.warn("请输入新闻！");
        return;
      }
    }
    console.log(formInfo, content);
    setCurrent(current + 1);
  };

  const handlePrevious = () => {
    setCurrent(current - 1);
  };

  const [categoryList, setCategoryList] = useState([]);

  useEffect(() => {
    const fetchDate = async () => {
      const { data } = await axios.get("/categories");
      setCategoryList(data);
    };
    fetchDate();
  }, []);

  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 20 },
  };

  const NewsForm = useRef(null);
  const [formInfo, setFormInfo] = useState({});
  const [content, setContent] = useState("");

  const User = JSON.parse(localStorage.getItem("user"));

  const handelSave = async (type) => {
    const req = {
      ...formInfo,
      content: content,
      region: User.region ? User.region : "全球",
      author: User.username,
      roleId: User.roleId,
      auditState: type,
      publishState: 0,
      createTime: Date.now(),
      star: 0,
      view: 0,
    };
    const res = await axios.post("/news", req);
    if (res.status === 201) {
      notification.info({
        message: "新闻提交成功",
        description: "您的新闻已经成功保存！",
        placement: "bottomRight",
      });
      props.history.push(
        type === 0 ? "/news-manage/draft" : "/audit-manage/list"
      );
    }
  };

  return (
    <div>
      <PageHeader
        className="site-page-header"
        title="攥写新闻"
        subTitle="编写您的新闻"
      />
      <Steps current={current}>
        <Step title="基本信息" description="新闻标题 新闻分类" />
        <Step title="新闻内容" description="新闻主体内容" />
        <Step title="新闻提交" description="保存草稿或者提交审核" />
      </Steps>

      <div className="content" style={{ marginTop: 50 }}>
        {/* v-show */}
        <div className={current === 0 ? "" : style.active}>
          <Form ref={NewsForm} {...layout}>
            <Form.Item
              name="title"
              label="新闻标题"
              rules={[{ required: true, message: "不能为空" }]}
            >
              <Input placeholder="请输入用户名"></Input>
            </Form.Item>
            <Form.Item
              name="categoryId"
              label="新闻分类"
              rules={[{ required: true, message: "不能为空" }]}
            >
              <Select placeholder="请选择">
                {categoryList.map((item) => (
                  <Option key={item.id} value={item.id}>
                    {item.title}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Form>
        </div>
        <div className={current === 1 ? "" : style.active}>
          <NewsEditor
            getContent={(value) => {
              console.log(value);
              setContent(value);
            }}
          ></NewsEditor>
        </div>
      </div>

      <div style={{ marginTop: 50, textAlign: "right" }}>
        <Space>
          {current === 2 && (
            <>
              <Button type="primary" onClick={() => handelSave(1)}>
                提交审核
              </Button>
              <Button ghost type="primary" onClick={() => handelSave(0)}>
                保存草稿
              </Button>
            </>
          )}
          {current < 2 && (
            <Button type="primary" onClick={handleNext}>
              下一步
            </Button>
          )}
          {current > 0 && <Button onClick={handlePrevious}>上一步</Button>}
        </Space>
      </div>
    </div>
  );
}
